const express = require('express')
const fs = require('fs')
const promisify = require('util').promisify
const readFile = promisify(fs.readFile)

const app = express()

app.use((req, res, next) => {
  console.log(req.url)
  next()
})

app.use(express.static('public'))


app.get('/', (req, res) => {
  // 对客户端做出响应 send方法会根据内容的类型自动设置请求头
  res.send('Hello Express')
})

app.use('/home', (req, res, next) => {
  console.log('home use = ' + req.url)
  next()
})

app.get('/home/set', (req, res) => {
  res.send('<h1>Hello Express</h1><p>' + req.url + '</p>')
})

app.get('/list', (_, res) => {
  res.send({
    name: '张三',
    age: 18
  })
})

// 中间件
app.get('/request', (req, res, next) => {
  req.name = '张三'
  next()
})

app.get('/request', (req, res) => {
  res.send(req.name)
})

app.get('/index', (req, res) => {
  throw new Error('我们自己抛出的错误')
})

app.get('/file', (req, res, next) => {
  fs.readFile('HelloWorld.js', 'utf8', (err, result) => {
    if (err) {
      next(err)
    } else {
      res.send(`<pre>${result}</pre>`)
    }
  })
})

app.get('/file2', async (req, res, next) => {
  /* const result = await readFile('XXX.js', 'utf8').catch((e) => {
    next(e)
  })
  console.log('继续往下走了  ' + result)
  if (result) {
    res.send(`<pre>${result}</pre>`)
  } */
  try {
   const result =  await readFile('HelloWorld.js', 'utf8')
   console.log('没有继续走')
   res.send(`<pre>${result}</pre>`)
  } catch (error) {
    next(error)
  }
  console.log('继续往下走了')
})

app.use((req, res) => {
  res.status(404).send('页面不存在')
})

// 错误处理中间件
app.use((err, req, res, next) => {
  console.log('错误处理中间件')
  res.status(500).send('服务器发生未知错误 -- ' + err.message)
})

app.listen(3000)
console.log('网站服务器启动成功')
